Escaping Perl regexp meta-characters
June 22, 2006 3:38 PM Subscribe
What's the best way to escape meta-characters in Perl regular expressions?
I'm doing some text parsing in Perl and a lot of my data includes parentheses which Perl interprets as grouping characters in regular experessions, which throws off my results.
For instance if $name = "Homer (Big Tuna) Simpson", then the expression
if($test_name =~ /$name/)
{
...
where $test_name is identical to $name doesn't return the correct results for me because the parentheses in the variable are intepreted as part of the expression and not the string.
I'd like to temporarily escape my strings long enough to test them, but then throw away the escaped version and use the original.
Is there a built-in function or module that would do this, or could someone suggest a quick and dirty sub to handle this?
I'm doing some text parsing in Perl and a lot of my data includes parentheses which Perl interprets as grouping characters in regular experessions, which throws off my results.
For instance if $name = "Homer (Big Tuna) Simpson", then the expression
if($test_name =~ /$name/)
{
...
where $test_name is identical to $name doesn't return the correct results for me because the parentheses in the variable are intepreted as part of the expression and not the string.
I'd like to temporarily escape my strings long enough to test them, but then throw away the escaped version and use the original.
Is there a built-in function or module that would do this, or could someone suggest a quick and dirty sub to handle this?
Best answer:
See also quotemeta
posted by Zed_Lopez at 3:46 PM on June 22, 2006
if($test_name =~ /\Q$name\E/)
See also quotemeta
posted by Zed_Lopez at 3:46 PM on June 22, 2006
If all you ever need is a case-sensitive substring search as in your example, you can get away with using
posted by harmfulray at 4:06 PM on June 22, 2006
index STR,SUBSTR
, which returns the index of the first occurrence of the substring within the string or -1 if not found, and which doesn't require escaping anything. As an added bonus, index
will be faster than a regex search.posted by harmfulray at 4:06 PM on June 22, 2006
Response by poster: Thanks, Hive Mind. quotemeta it is.
posted by hwestiii at 4:31 PM on June 22, 2006
posted by hwestiii at 4:31 PM on June 22, 2006
This thread is closed to new comments.
$test_name =~ /\Q$name\E/
posted by xiojason at 3:46 PM on June 22, 2006